package com.icss.clothes.cotroller;

import com.icss.clothes.entity.Buy;
import com.icss.clothes.entity.User;
import com.icss.clothes.service.imp.BuyService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * 购物车的控制器类
 */
@Controller
public class BuyShopController {

    @Autowired
    private BuyService buyService;

    // 将商品加入购物车
    @RequestMapping("/addCart")

    public ModelAndView addCart(Buy buy,HttpSession session) {
        ModelAndView modelAndView = new ModelAndView("forward:/lookCart");
        User user = (User) session.getAttribute("loginUser");
        if (user==null) {
            modelAndView.setViewName("login");
            modelAndView.addObject("msg", "请先登录！");
            return modelAndView;
        }
        buy.setUser_id(user.getUser_id());
        //buy.setTotalPrice(buy.getC_price() * buy.getQuantity());
        buyService.addCar(buy);
//        modelAndView.addObject("msg","购物车添加成功！");
        return modelAndView;
    }
    //查看购物车
    @RequestMapping("/lookCart")
    public ModelAndView lookCart(HttpSession session){
        ModelAndView modelAndView = new ModelAndView("cart");
        User user = (User) session.getAttribute("loginUser");
        if (user==null) {
            modelAndView.setViewName("login");
            modelAndView.addObject("msg", "请先登录！");
            return modelAndView;
        }
        List<Buy> carList= buyService.findCarList(user.getUser_id());
        modelAndView.addObject("carList",carList);
        return modelAndView;
    }
    //删除购物车商品
    @RequestMapping("/deleteCart")
    @ResponseBody
    public ModelAndView deleteCart(int car_id){
        ModelAndView modelAndView = new ModelAndView("cart");
        buyService.deleteCar(car_id);
       // modelAndView.addObject("msg","删除成功！");
        return modelAndView;
    }

    //用于头部购物车展示
    @RequestMapping("/showCartInTop")
    public ModelAndView showCartInTop(HttpSession session){
      ModelAndView modelAndView = new ModelAndView("top");
        User user = (User) session.getAttribute("loginUser");
       List<Buy> topCarList=buyService.findCarListInTop(user.getUser_id());
       modelAndView.addObject("topCarList",topCarList);
        return modelAndView;
}
}

